package com.ehsunbehravesh.mypasswords.gui;

import com.ehsunbehravesh.mypasswords.resource.ExportDialog;
import com.ehsunbehravesh.mypasswords.Domain;
import com.ehsunbehravesh.mypasswords.Logger;
import com.ehsunbehravesh.mypasswords.PasswordAnalyser;
import com.ehsunbehravesh.mypasswords.Utils;
import com.ehsunbehravesh.mypasswords.VersionChecker;
import com.ehsunbehravesh.mypasswords.entity.PasswordEntry;
import com.ehsunbehravesh.mypasswords.entity.PasswordTag;
import com.ehsunbehravesh.mypasswords.multilingual.LanguageException;
import com.ehsunbehravesh.mypasswords.multilingual.LanguageManager;
import com.ehsunbehravesh.mypasswords.resource.ResourceLoader;
import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.swing.Timer;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.xml.parsers.ParserConfigurationException;
import net.java.balloontip.BalloonTip;
import net.java.balloontip.BalloonTip.AttachLocation;
import net.java.balloontip.BalloonTip.Orientation;
import net.java.balloontip.styles.BalloonTipStyle;
import net.java.balloontip.styles.RoundedBalloonStyle;
import net.java.balloontip.utils.TimingUtils;
import org.xml.sax.SAXException;
import com.ehsunbehravesh.mypasswords.RealtimePasswordValidator;
import java.util.*;

public class MainFrame extends javax.swing.JFrame implements ClipboardOwner {

  private static final Color StatusNewColor = new Color(102, 153, 255);
  private static final Color StatusUpdateColor = new Color(0, 204, 51);
  private PasswordEntry passwordEntry;
  private boolean showPassword;
  private boolean showTitleBaloon;
  private Timer lockTimer;
  private boolean locked;
  private AboutDialog aboutDialog;
  private PasswordGeneratorDialog passwordGeneratorDialog;
  private JComboBox cmbLanguages;
  private Timer timerToolbarDecoration;
  private String selectedLanguage;
  private String[] availableLanguages;
  private String newPasswordCaption = "New Password";
  private String updatePasswordCaption = "Update Password";
  private Properties englishLanguage;
  private Properties currentLanguage;
  private String invalidDecryptionKey = "Invalid Decryption Key!";
  private String areAllFieldsEncrypted = "Are all fields encrypted?";
  private String pleaseEnterTheKey = "Please enter the key which you have encrypted the file with:";
  private String deletedSuccessfully = "Password deleted successfully.";
  private String errorOccured = "Error occured! Please see the log file for more details.";
  private String doYouWantToDelete = "<html>Do you want to delete the <b>%s</b> password?</html>";
  private String deleteCaption = "Delete";
  private String errorCaption = "Error";
  private String informationCaption = "Information";
  private String passwordSaved = "Password saved successfully.";
  private String warningCaption = "Warning";
  private String youMustChooseATitle = "You must choose a title!";
  private String selectAFileNot = "Select a file, not a directory!";
  private String invalidFileExtension = "Invalid file extension!";
  private String decryptionKey = "Decryption Key";
  private String security = "Security";
  private String yesCaption = "Yes";
  private String noCaption = "No";
  private String okCaption = "OK";
  private String cancelCaption = "Cancel";
  private String confirmDoesNotMatch = "Confirmation password does not match!";
  private RealtimePasswordValidator passVal;
  private boolean surveyDisplayed = false;

  public MainFrame(AboutDialog aboutDialog, PasswordGeneratorDialog passwordGeneratorDialog) {
    try {
      this.aboutDialog = aboutDialog;
      this.passwordGeneratorDialog = passwordGeneratorDialog;

      initComponents();
      myInitComponents();
      loadOptions();
      //checkLanguages();     
      
    } catch (Exception ex) {
      Logger.log(ex.getMessage());
    }

    // check database connectivity    
    Domain domain = Domain.getInstance();
    Connection con = domain.getDBConnection();
    if (con != null) {
      try {
        con.close();
      } catch (SQLException ex) {
        Logger.log(ex.getMessage());
      }
    } else {
      JOptionPane.showMessageDialog(this, "Connection to the database failed!", "Error", JOptionPane.ERROR_MESSAGE);
      System.exit(0);
    }

    // check new version
    try {
      checkForNewerVersion();
    } catch (Exception ex) {
      Logger.log(ex.getMessage());
    }

    // Timer of locking
    this.locked = false;
    this.lockTimer = new Timer(30000, new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        lockTimerActionPerformed();
      }
    });

    this.lockTimer.start();
  }

  @Override
  protected void finalize() throws Throwable {
    super.finalize();
  }

  @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlMain = new javax.swing.JPanel();
        tlbMain = new javax.swing.JToolBar();
        jLabel8 = new javax.swing.JLabel();
        btnShowPassword = new javax.swing.JToggleButton();
        btnDelete = new javax.swing.JButton();
        btnSearch = new javax.swing.JButton();
        btnBrows = new javax.swing.JButton();
        jLabel14 = new javax.swing.JLabel();
        btnImport = new javax.swing.JButton();
        btnExport = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        btnChangePassword = new javax.swing.JButton();
        btnPasswordGenerator = new javax.swing.JButton();
        btnEncryptor = new javax.swing.JButton();
        jLabel11 = new javax.swing.JLabel();
        btnSettings = new javax.swing.JButton();
        btnAbout = new javax.swing.JButton();
        lblStatus = new javax.swing.JLabel();
        lblTitle = new javax.swing.JLabel();
        txtTitle = new javax.swing.JTextField();
        lblDescription = new javax.swing.JLabel();
        txtDescription = new javax.swing.JTextField();
        lblUsername = new javax.swing.JLabel();
        txtUsername = new javax.swing.JTextField();
        lblPassword2 = new javax.swing.JLabel();
        txtPassword = new javax.swing.JPasswordField();
        lblPassword = new javax.swing.JLabel();
        lblConfirmation2 = new javax.swing.JLabel();
        txtConfirmation = new javax.swing.JPasswordField();
        lblConfirmation = new javax.swing.JLabel();
        lblStrength2 = new javax.swing.JLabel();
        lblStrength = new javax.swing.JLabel();
        lblURL = new javax.swing.JLabel();
        txtURL = new javax.swing.JTextField();
        lblTags = new javax.swing.JLabel();
        txtTags = new javax.swing.JTextField();
        btnSave = new javax.swing.JButton();
        btnNew = new javax.swing.JButton();
        confValLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("MyPasswords"); // NOI18N
        setBackground(new java.awt.Color(255, 255, 255));
        setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        setLocationByPlatform(true);
        setResizable(false);
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });
        addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                formFocusGained(evt);
            }
        });

        pnlMain.setBackground(new java.awt.Color(255, 255, 255));

        tlbMain.setBackground(new java.awt.Color(255, 255, 255));
        tlbMain.setFloatable(false);
        tlbMain.setRollover(true);

        jLabel8.setText("  "); // NOI18N
        tlbMain.add(jLabel8);

        btnShowPassword.setBackground(new java.awt.Color(255, 255, 255));
        btnShowPassword.setMnemonic(KeyEvent.VK_F3);
        btnShowPassword.setText("show"); // NOI18N
        btnShowPassword.setToolTipText("Show Password (ALT + F3)"); // NOI18N
        btnShowPassword.setFocusable(false);
        btnShowPassword.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnShowPassword.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnShowPassword.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnShowPasswordActionPerformed(evt);
            }
        });
        tlbMain.add(btnShowPassword);

        btnDelete.setBackground(new java.awt.Color(255, 255, 255));
        btnDelete.setMnemonic(KeyEvent.VK_DELETE);
        btnDelete.setText("delete"); // NOI18N
        btnDelete.setToolTipText("Delete Password (ALT + DELETE)"); // NOI18N
        btnDelete.setEnabled(false);
        btnDelete.setFocusable(false);
        btnDelete.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnDelete.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });
        tlbMain.add(btnDelete);

        btnSearch.setBackground(new java.awt.Color(255, 255, 255));
        btnSearch.setMnemonic(KeyEvent.VK_F);
        btnSearch.setText("search"); // NOI18N
        btnSearch.setToolTipText("Search (ALT + F)"); // NOI18N
        btnSearch.setFocusable(false);
        btnSearch.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnSearch.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });
        tlbMain.add(btnSearch);

        btnBrows.setBackground(new java.awt.Color(255, 255, 255));
        btnBrows.setMnemonic(KeyEvent.VK_T);
        btnBrows.setText("browse"); // NOI18N
        btnBrows.setToolTipText("Browse (ALT + T)"); // NOI18N
        btnBrows.setFocusable(false);
        btnBrows.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnBrows.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnBrows.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBrowsActionPerformed(evt);
            }
        });
        tlbMain.add(btnBrows);

        jLabel14.setBackground(new java.awt.Color(255, 255, 255));
        jLabel14.setForeground(new java.awt.Color(204, 204, 204));
        jLabel14.setText(" | "); // NOI18N
        tlbMain.add(jLabel14);

        btnImport.setBackground(java.awt.Color.white);
        btnImport.setText("import"); // NOI18N
        btnImport.setToolTipText("Import from XML file"); // NOI18N
        btnImport.setFocusable(false);
        btnImport.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnImport.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnImport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImportActionPerformed(evt);
            }
        });
        tlbMain.add(btnImport);

        btnExport.setBackground(java.awt.Color.white);
        btnExport.setText("export"); // NOI18N
        btnExport.setToolTipText("Export to XML file"); // NOI18N
        btnExport.setFocusable(false);
        btnExport.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnExport.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnExport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportActionPerformed(evt);
            }
        });
        tlbMain.add(btnExport);

        jLabel10.setBackground(new java.awt.Color(255, 255, 255));
        jLabel10.setForeground(new java.awt.Color(204, 204, 204));
        jLabel10.setText(" | "); // NOI18N
        tlbMain.add(jLabel10);

        btnChangePassword.setBackground(new java.awt.Color(255, 255, 255));
        btnChangePassword.setText("change"); // NOI18N
        btnChangePassword.setToolTipText("Change Password"); // NOI18N
        btnChangePassword.setFocusable(false);
        btnChangePassword.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnChangePassword.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnChangePassword.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnChangePasswordActionPerformed(evt);
            }
        });
        tlbMain.add(btnChangePassword);

        btnPasswordGenerator.setBackground(new java.awt.Color(255, 255, 255));
        btnPasswordGenerator.setText("generator"); // NOI18N
        btnPasswordGenerator.setToolTipText("Password Generator"); // NOI18N
        btnPasswordGenerator.setFocusable(false);
        btnPasswordGenerator.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnPasswordGenerator.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnPasswordGenerator.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPasswordGeneratorActionPerformed(evt);
            }
        });
        tlbMain.add(btnPasswordGenerator);

        btnEncryptor.setBackground(new java.awt.Color(255, 255, 255));
        btnEncryptor.setText("encryptor"); // NOI18N
        btnEncryptor.setToolTipText("Encryptor"); // NOI18N
        btnEncryptor.setFocusable(false);
        btnEncryptor.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnEncryptor.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEncryptor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEncryptorActionPerformed(evt);
            }
        });
        tlbMain.add(btnEncryptor);

        jLabel11.setBackground(new java.awt.Color(255, 255, 255));
        jLabel11.setForeground(new java.awt.Color(204, 204, 204));
        jLabel11.setText(" | "); // NOI18N
        tlbMain.add(jLabel11);

        btnSettings.setBackground(new java.awt.Color(255, 255, 255));
        btnSettings.setText("settings");
        btnSettings.setToolTipText("Settings");
        btnSettings.setFocusable(false);
        btnSettings.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnSettings.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnSettings.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSettingsActionPerformed(evt);
            }
        });
        tlbMain.add(btnSettings);

        btnAbout.setBackground(new java.awt.Color(255, 255, 255));
        btnAbout.setText("about"); // NOI18N
        btnAbout.setToolTipText("About MyPassword"); // NOI18N
        btnAbout.setFocusable(false);
        btnAbout.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAbout.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAbout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAboutActionPerformed(evt);
            }
        });
        tlbMain.add(btnAbout);

        lblStatus.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        lblStatus.setForeground(new java.awt.Color(102, 153, 255));
        lblStatus.setText("New Password"); // NOI18N

        lblTitle.setText("Title:"); // NOI18N

        txtTitle.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtTitleFocusLost(evt);
            }
        });
        txtTitle.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtTitleKeyPressed(evt);
            }
        });

        lblDescription.setText("Description:"); // NOI18N

        lblUsername.setText("Username:"); // NOI18N

        lblPassword2.setText("Password:"); // NOI18N

        txtPassword.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtPasswordMouseClicked(evt);
            }
        });
        txtPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtPasswordKeyReleased(evt);
            }
        });

        lblPassword.setText(" "); // NOI18N
        lblPassword.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lblPasswordMouseClicked(evt);
            }
        });

        lblConfirmation2.setText("Confirmation:"); // NOI18N

        txtConfirmation.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtConfirmationKeyReleased(evt);
            }
        });

        lblConfirmation.setText(" "); // NOI18N

        lblStrength2.setText("Strength:"); // NOI18N

        lblStrength.setText("strength"); // NOI18N

        lblURL.setText("URL:"); // NOI18N

        txtURL.setForeground(new java.awt.Color(9, 20, 248));
        txtURL.setText("http://"); // NOI18N
        txtURL.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
        txtURL.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                txtURLMousePressed(evt);
            }
        });
        txtURL.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                txtURLMouseMoved(evt);
            }
        });
        txtURL.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtURLFocusGained(evt);
            }
        });

        lblTags.setText("Tags:"); // NOI18N

        txtTags.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtTagsKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtTagsKeyReleased(evt);
            }
        });

        btnSave.setMnemonic(KeyEvent.VK_S);
        btnSave.setText("Save"); // NOI18N
        btnSave.setToolTipText("ALT + S");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnNew.setMnemonic(KeyEvent.VK_N);
        btnNew.setText("New"); // NOI18N
        btnNew.setToolTipText("ALT + N");
        btnNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlMainLayout = new javax.swing.GroupLayout(pnlMain);
        pnlMain.setLayout(pnlMainLayout);
        pnlMainLayout.setHorizontalGroup(
            pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlMainLayout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addGroup(pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlMainLayout.createSequentialGroup()
                        .addComponent(lblStatus)
                        .addContainerGap())
                    .addGroup(pnlMainLayout.createSequentialGroup()
                        .addGroup(pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblTitle)
                            .addComponent(lblDescription)
                            .addComponent(lblUsername)
                            .addComponent(lblPassword2)
                            .addComponent(lblConfirmation2)
                            .addComponent(lblStrength2)
                            .addComponent(lblURL)
                            .addGroup(pnlMainLayout.createSequentialGroup()
                                .addGap(7, 7, 7)
                                .addComponent(lblTags)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(confValLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtDescription, javax.swing.GroupLayout.DEFAULT_SIZE, 607, Short.MAX_VALUE)
                            .addComponent(txtTitle, javax.swing.GroupLayout.DEFAULT_SIZE, 607, Short.MAX_VALUE)
                            .addComponent(txtUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 607, Short.MAX_VALUE)
                            .addGroup(pnlMainLayout.createSequentialGroup()
                                .addGroup(pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtConfirmation, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(18, 18, 18)
                                .addGroup(pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblConfirmation, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE)
                                    .addComponent(lblPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE)))
                            .addComponent(lblStrength, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtURL, javax.swing.GroupLayout.DEFAULT_SIZE, 607, Short.MAX_VALUE)
                            .addComponent(txtTags, javax.swing.GroupLayout.DEFAULT_SIZE, 607, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlMainLayout.createSequentialGroup()
                                .addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 267, Short.MAX_VALUE)
                                .addComponent(btnNew, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(26, 26, 26))))
            .addComponent(tlbMain, javax.swing.GroupLayout.DEFAULT_SIZE, 759, Short.MAX_VALUE)
        );
        pnlMainLayout.setVerticalGroup(
            pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlMainLayout.createSequentialGroup()
                .addComponent(tlbMain, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(lblStatus)
                .addGap(25, 25, 25)
                .addGroup(pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblTitle))
                .addGap(18, 18, 18)
                .addGroup(pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtDescription, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblDescription))
                .addGap(18, 18, 18)
                .addGroup(pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblUsername))
                .addGap(18, 18, 18)
                .addGroup(pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblPassword)
                    .addComponent(lblPassword2))
                .addGap(18, 18, 18)
                .addGroup(pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlMainLayout.createSequentialGroup()
                        .addGroup(pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtConfirmation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblConfirmation)
                            .addComponent(lblConfirmation2))
                        .addGap(18, 18, 18)
                        .addGroup(pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblStrength)
                            .addComponent(lblStrength2))
                        .addGap(18, 18, 18)
                        .addGroup(pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtURL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblURL))
                        .addGap(18, 18, 18)
                        .addGroup(pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtTags, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblTags))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                        .addGroup(pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnSave)
                            .addComponent(btnNew))
                        .addGap(22, 22, 22))
                    .addGroup(pnlMainLayout.createSequentialGroup()
                        .addComponent(confValLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlMain, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlMain, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

  private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
    saveOptions();
    Logger.log("Exit.");
  }//GEN-LAST:event_formWindowClosing

  private void txtTagsKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTagsKeyReleased
    txtTagsKeyRelease(evt);
  }//GEN-LAST:event_txtTagsKeyReleased

  private void btnNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewActionPerformed
    newPasswordEntry();
    displaySurvey();
  }//GEN-LAST:event_btnNewActionPerformed

  private void txtTitleFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtTitleFocusLost
    String title = txtTitle.getText().trim();
    if (passwordEntry == null) {
      passwordEntry = new PasswordEntry(title);
    } else {
      passwordEntry.setTitle(title);
    }

    if (passwordEntry.loadByTitle(false) && passwordEntry.getId() > 0) {
      displayPasswordEntry();
      if (title.length() <= 0) {
        showBaloon(txtTitle, "<html>Empty title means <span style='color: red; font-weight: bold'>Delete</span>.</html>", new Color(240, 240, 240, 250), new Color(200, 200, 200, 255), 5000);
      }
    }
  }//GEN-LAST:event_txtTitleFocusLost

  private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
    if (txtTitle.getText().trim().length() > 0) {
      if (checkPasswords()) {
        if (passwordEntry == null) {
          passwordEntry = new PasswordEntry();
        }

        passwordEntry.setTitle(txtTitle.getText().trim());
        passwordEntry.setDescription(txtDescription.getText().trim());
        passwordEntry.setUsername(txtUsername.getText().trim());
        passwordEntry.setUrl(txtURL.getText().trim());
        passwordEntry.setPassword(txtPassword.getPassword());

        if (passwordEntry.save()) {
          passwordEntry.clearTags();
          StringTokenizer tokenTags = new StringTokenizer(txtTags.getText(), ",");
          while (tokenTags.hasMoreTokens()) {
            String tag = tokenTags.nextToken().trim();
            passwordEntry.addTag(tag);
          }
          JOptionPane.showMessageDialog(this, passwordSaved, informationCaption, JOptionPane.INFORMATION_MESSAGE);
          PasswordTag.cleanTags();
          lblStatus.setText(updatePasswordCaption);
          lblStatus.setForeground(StatusUpdateColor);
          btnDelete.setEnabled(true);
        } else {
          JOptionPane.showMessageDialog(this, errorOccured, errorCaption, JOptionPane.ERROR_MESSAGE);
        }
      } else {
        JOptionPane.showMessageDialog(this, confirmDoesNotMatch, warningCaption, JOptionPane.WARNING_MESSAGE);
      }
    } else {
      if (lblStatus.getText().toLowerCase().trim().equals(newPasswordCaption)) {
        JOptionPane.showMessageDialog(this, youMustChooseATitle, warningCaption, JOptionPane.WARNING_MESSAGE);
        txtTitle.requestFocus();
      } else {
        if (passwordEntry != null && passwordEntry.getId() > 0) {
          deletePasswordEntry();
        }
      }
    }
  }//GEN-LAST:event_btnSaveActionPerformed

  private void txtURLFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtURLFocusGained
    if (txtURL.getText().toLowerCase().equals("http://")) {
      txtURL.setSelectionStart(0);
      txtURL.setSelectionEnd(txtURL.getText().length());
    }
  }//GEN-LAST:event_txtURLFocusGained

  private void btnShowPasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnShowPasswordActionPerformed
    toggleShowPassword();
  }//GEN-LAST:event_btnShowPasswordActionPerformed

  private void txtPasswordKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPasswordKeyReleased
    String confPassword = new String(txtConfirmation.getPassword());
    String password = new String(txtPassword.getPassword());
    lblPassword.setText(password);
    if (password.length() > 0) {
      showStars(password);
    } else {
      hideStars();
    }
    if (!confPassword.equals("")) { //which means that evaluation should take place.
      ImageIcon res = passVal.validatePasswords(password, confPassword);
      //depending on the evaluation and existing icon, we update the image in the confirmation field.
      if (confValLabel.getIcon() == null) { //icon is null => update icon
        confValLabel.setIcon(res);
      } else if (!confValLabel.getIcon().equals(res)) { //icon is not the same => update icon
        confValLabel.setIcon(res);
      }
    }
  }//GEN-LAST:event_txtPasswordKeyReleased

  private void txtConfirmationKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtConfirmationKeyReleased
    String confPassword = new String(txtConfirmation.getPassword());
    String password = new String(txtPassword.getPassword());
    lblConfirmation.setText(confPassword);
    if (confPassword.equals("")) { //confPassword has nothing inside => set Icon to null.
      confValLabel.setIcon(null);
    } else { //confPassword has something inside, run the evaluation.
      ImageIcon res = passVal.validatePasswords(password, confPassword);
      if (confValLabel.getIcon() == null) { //icon is null => update icon
        confValLabel.setIcon(res);
      } else if (!confValLabel.getIcon().equals(res)) {//icon is not the same => update icon
        confValLabel.setIcon(res);
      }
    }
  }//GEN-LAST:event_txtConfirmationKeyReleased

  private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
    SearchDialog searchDialog = new SearchDialog(this, true);
    try {
      searchDialog.setVisible(true);
    } finally {
      searchDialog.dispose();
      searchDialog = null;
    }
  }//GEN-LAST:event_btnSearchActionPerformed

  private void txtTagsKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTagsKeyPressed
    txtTagsKeyPress(evt);
  }//GEN-LAST:event_txtTagsKeyPressed

  private void btnChangePasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChangePasswordActionPerformed
    ChangePasswordDialog2 changePasswordDialog = new ChangePasswordDialog2(this, true);
    try {
      changePasswordDialog.setVisible(true);
    } finally {
      changePasswordDialog.dispose();
      changePasswordDialog = null;
    }
  }//GEN-LAST:event_btnChangePasswordActionPerformed

  private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
    deletePasswordEntry();
  }//GEN-LAST:event_btnDeleteActionPerformed

  private void btnAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAboutActionPerformed
    about();
  }//GEN-LAST:event_btnAboutActionPerformed

  private void btnImportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImportActionPerformed
    importFromXML();
  }//GEN-LAST:event_btnImportActionPerformed

  private void btnExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportActionPerformed
    exportFromXML();
  }//GEN-LAST:event_btnExportActionPerformed

  private void lblPasswordMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblPasswordMouseClicked
    if (SwingUtilities.isRightMouseButton(evt)) {
      Point point = evt.getPoint();
      mnuPassword.show(lblPassword, point.x, point.y);
    }
  }//GEN-LAST:event_lblPasswordMouseClicked

  private void txtPasswordMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtPasswordMouseClicked
    if (SwingUtilities.isRightMouseButton(evt)) {
      Point point = evt.getPoint();
      mnuPassword.show(txtPassword, point.x, point.y);
    }
  }//GEN-LAST:event_txtPasswordMouseClicked

  private void btnPasswordGeneratorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPasswordGeneratorActionPerformed
    btnPasswordGeneratorActionPerform(evt);
  }//GEN-LAST:event_btnPasswordGeneratorActionPerformed

  private void txtTitleKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTitleKeyPressed
    txtTitleKeyPress(evt);
  }//GEN-LAST:event_txtTitleKeyPressed

  private void formFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_formFocusGained
    if (this.locked) {
      unlock();
    }
  }//GEN-LAST:event_formFocusGained

  private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
    if (this.locked) {
      unlock();
    }
  }//GEN-LAST:event_formMouseClicked

  private void txtURLMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtURLMousePressed
    if (evt.getModifiers() == 18) {
      Utils.openURL(txtURL.getText());
    }
  }//GEN-LAST:event_txtURLMousePressed

  private void txtURLMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtURLMouseMoved
    if (evt.getModifiers() == 2) { // CTRL
      txtURL.setCursor(new Cursor(Cursor.HAND_CURSOR));
    } else {
      txtURL.setCursor(new Cursor(Cursor.TEXT_CURSOR));
    }
  }//GEN-LAST:event_txtURLMouseMoved

  private void btnBrowsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBrowsActionPerformed
    showBrows();
  }//GEN-LAST:event_btnBrowsActionPerformed

  private void btnEncryptorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEncryptorActionPerformed
    showEncryptor();
  }//GEN-LAST:event_btnEncryptorActionPerformed

  private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
    authenticate();
    askForDonation();
  }//GEN-LAST:event_formWindowOpened

  private void btnSettingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSettingsActionPerformed
    btnSettingsActionPerform(evt);
  }//GEN-LAST:event_btnSettingsActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAbout;
    private javax.swing.JButton btnBrows;
    private javax.swing.JButton btnChangePassword;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEncryptor;
    private javax.swing.JButton btnExport;
    private javax.swing.JButton btnImport;
    private javax.swing.JButton btnNew;
    private javax.swing.JButton btnPasswordGenerator;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnSearch;
    private javax.swing.JButton btnSettings;
    private javax.swing.JToggleButton btnShowPassword;
    private javax.swing.JLabel confValLabel;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel lblConfirmation;
    private javax.swing.JLabel lblConfirmation2;
    private javax.swing.JLabel lblDescription;
    private javax.swing.JLabel lblPassword;
    private javax.swing.JLabel lblPassword2;
    private javax.swing.JLabel lblStatus;
    private javax.swing.JLabel lblStrength;
    private javax.swing.JLabel lblStrength2;
    private javax.swing.JLabel lblTags;
    private javax.swing.JLabel lblTitle;
    private javax.swing.JLabel lblURL;
    private javax.swing.JLabel lblUsername;
    private javax.swing.JPanel pnlMain;
    private javax.swing.JToolBar tlbMain;
    private javax.swing.JPasswordField txtConfirmation;
    private javax.swing.JTextField txtDescription;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JTextField txtTags;
    private javax.swing.JTextField txtTitle;
    private javax.swing.JTextField txtURL;
    private javax.swing.JTextField txtUsername;
    // End of variables declaration//GEN-END:variables
  private JPopupMenu mnuPassword;
  private JMenuItem mniCopy, mniPaste;

  //<editor-fold desc="Methods">
  private void myInitComponents() {
    pnlMain.setVisible(false);
    Domain domain = Domain.getInstance();
    try {
      URL url = ResourceLoader.class.getResource("safe32.png");
      ImageIcon safeIcon = new ImageIcon(url);
      setIconImage(safeIcon.getImage());

      url = ResourceLoader.class.getResource("safe.png");
      btnAbout.setIcon(new ImageIcon(url));
      btnAbout.setText("");

      url = ResourceLoader.class.getResource("eye.png");
      btnShowPassword.setIcon(new ImageIcon(url));
      btnShowPassword.setText("");

      url = ResourceLoader.class.getResource("search.png");
      btnSearch.setIcon(new ImageIcon(url));
      btnSearch.setText("");

      url = ResourceLoader.class.getResource("tree.png");
      btnBrows.setIcon(new ImageIcon(url));
      btnBrows.setText("");

      url = ResourceLoader.class.getResource("password2.png");
      btnChangePassword.setIcon(new ImageIcon(url));
      btnChangePassword.setText("");

      url = ResourceLoader.class.getResource("delete.png");
      btnDelete.setIcon(new ImageIcon(url));
      url = ResourceLoader.class.getResource("disableddelete.png");
      btnDelete.setDisabledIcon(new ImageIcon(url));
      btnDelete.setText("");

      url = ResourceLoader.class.getResource("export.png");
      btnExport.setIcon(new ImageIcon(url));
      btnExport.setText("");

      url = ResourceLoader.class.getResource("import.png");
      btnImport.setIcon(new ImageIcon(url));
      btnImport.setText("");

      url = ResourceLoader.class.getResource("0stars.png");
      lblStrength.setIcon(new ImageIcon(url));
      lblStrength.setText("");

      url = ResourceLoader.class.getResource("password_generator.png");
      btnPasswordGenerator.setIcon(new ImageIcon(url));
      btnPasswordGenerator.setText("");

      url = ResourceLoader.class.getResource("settings.png");
      btnSettings.setIcon(new ImageIcon(url));
      btnSettings.setText("");

      url = ResourceLoader.class.getResource("lock.png");
      btnEncryptor.setIcon(new ImageIcon(url));
      btnEncryptor.setText("");

      //<editor-fold defaultstate="collapsed" desc="Password Popup Menu">
      mnuPassword = new JPopupMenu("Password");

      url = ResourceLoader.class.getResource("copy.png");
      mniCopy = new JMenuItem("Copy Password", new ImageIcon(url));

      url = ResourceLoader.class.getResource("paste.png");
      mniPaste = new JMenuItem("Paste Password", new ImageIcon(url));

      mnuPassword.add(mniCopy);
      mnuPassword.add(mniPaste);

      ActionListener menuActionListener = (new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
          if (e.getSource() == mniCopy) {
            mniCopyActionPerformed(e);
          } else {
            mniPasteActionPerformed(e);
            if (txtPassword.getPassword().length > 0) {
              showStars(new String(txtPassword.getPassword()));
            } else {
              hideStars();
            }
          }
        }
      });

      mniCopy.addActionListener(menuActionListener);
      mniPaste.addActionListener(menuActionListener);
      //</editor-fold>
      this.setTitle(this.getTitle() + " " + domain.getMyPasswordsVersion());
      passVal = new RealtimePasswordValidator();
    } catch (Exception ex) {
      Logger.log(ex.getMessage());
    }
  }

  private void mniCopyActionPerformed(ActionEvent e) {
    Utils.setClipboardContents(new String(txtPassword.getPassword()), this);
  }

  private void mniPasteActionPerformed(ActionEvent e) {
    String password = Utils.getClipboardContents();
    txtPassword.setText(password);
    txtConfirmation.setText(password);
    lblPassword.setText(password);
    lblConfirmation.setText(password);
  }

  private void setPosition() {
    Domain domain = Domain.getInstance();
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int x;
    int y;
    try {
      x = Integer.parseInt(domain.getSetting("main_frame_x", null));
    } catch (Exception ex) {
      x = 0;
    }
    try {
      y = Integer.parseInt(domain.getSetting("main_frame_y", null));
    } catch (Exception ex) {
      y = 0;
    }

    if (x > screenSize.width) {
      return;
    }
    if (y > screenSize.height) {
      return;
    }

    setLocation(x, y);
  }

  private String searchInTags(String keyword) {
    PasswordTag[] tags = PasswordTag.getAllTags();

    for (int i = 0; i < tags.length; i++) {
      PasswordTag passwordTag = tags[i];
      String tagTitle = passwordTag.getTitle();

      if (tagTitle.indexOf(keyword.toLowerCase()) == 0) {
        return tagTitle;
      }
    }
    return "";
  }

  private String searchInTitles(String keyword) {
    PasswordEntry[] passwordEntries = PasswordEntry.getAllPasswordEntries();

    for (int i = 0; i < passwordEntries.length; i++) {
      PasswordEntry currentPasswordEntry = passwordEntries[i];
      String title = currentPasswordEntry.getTitle();

      if (title.toLowerCase().indexOf(keyword.toLowerCase()) == 0) {
        return title;
      }
    }
    return "";
  }

  private boolean checkPasswords() {
    char[] password = txtPassword.getPassword();
    char[] confirmation = txtConfirmation.getPassword();
    return Arrays.equals(password, confirmation);
  }

  private void toggleShowPassword() {
    showPassword = btnShowPassword.isSelected();
    lblPassword.setVisible(showPassword);
    lblConfirmation.setVisible(showPassword);
  }

  private void loadOptions() {
    Domain domain = Domain.getInstance();

    String strShowPassword = domain.getSetting("show_password", null);
    try {
      showPassword = strShowPassword != null ? Boolean.parseBoolean(strShowPassword) : false;
    } catch (Exception ex) {
      showPassword = false;
    }

    String strShowTitleBaloon = domain.getSetting("show_title_baloon", null);
    try {
      showTitleBaloon = strShowTitleBaloon != null ? Boolean.parseBoolean(strShowTitleBaloon) : true;
    } catch (Exception ex) {
      showTitleBaloon = false;
    }

    setPosition();
    setComponentsStates();
  }

  private void saveOptions() {
    Domain domain = Domain.getInstance();
    domain.setSetting("main_frame_x", getX() + "", null);
    domain.setSetting("main_frame_y", getY() + "", null);
    domain.setSetting("show_password", showPassword + "", null);
  }

  private void setComponentsStates() {
    btnShowPassword.setSelected(showPassword);
    lblPassword.setVisible(showPassword);
    lblConfirmation.setVisible(showPassword);
  }
  //</editor-fold>;  

  private void suggestPasswordEntry() {
    if (txtTitle.getText().length() > 0) {
      String currentTitle = txtTitle.getText();
      String candidPasswordEntry = searchInTitles(currentTitle);
      if (candidPasswordEntry.length() > 0) {
        String restOfCandidTag = Utils.getRestOfStrings(currentTitle, candidPasswordEntry);
        txtTitle.setText(txtTitle.getText() + restOfCandidTag);
        txtTitle.setSelectionStart(txtTitle.getText().lastIndexOf(restOfCandidTag));
        txtTitle.setSelectionEnd(txtTitle.getText().length());
      }
    }
  }

  public void displayPasswordEntry() {
    if (passwordEntry == null || passwordEntry.getId() <= 0) {
      return;
    }

    txtTitle.setText(passwordEntry.getTitle());
    txtDescription.setText(passwordEntry.getDescription());
    txtUsername.setText(passwordEntry.getUsername());
    txtPassword.setText(passwordEntry.getPassword());
    txtConfirmation.setText(passwordEntry.getPassword());
    txtURL.setText(passwordEntry.getUrl());
    lblPassword.setText(passwordEntry.getPassword());
    lblConfirmation.setText(passwordEntry.getPassword());

    txtTags.setText("");
    PasswordTag[] tags = passwordEntry.readTags();
    for (int i = 0; i < tags.length; i++) {
      PasswordTag passwordTag = tags[i];
      txtTags.setText(txtTags.getText() + passwordTag.getTitle());
      if (i < tags.length - 1) {
        txtTags.setText(txtTags.getText() + ", ");
      }
    }
    lblStatus.setText(updatePasswordCaption);
    lblStatus.setForeground(StatusUpdateColor);
    btnDelete.setEnabled(true);

    if (passwordEntry.getPassword().length() > 0) {
      showStars(passwordEntry.getPassword());
    } else {
      hideStars();
    }
  }

  private void deletePasswordEntry() {
    //int answer = JOptionPane.showConfirmDialog(this, String.format(doYouWantToDelete, passwordEntry.getTitle()), deleteCaption, JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
    int answer = JOptionPane.showOptionDialog(this, String.format(doYouWantToDelete, passwordEntry.getTitle()), deleteCaption, JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, new String[]{yesCaption, noCaption}, noCaption);
    if (answer == JOptionPane.YES_OPTION) {
      if (passwordEntry.clearTags()) {
        if (passwordEntry.delete()) {
          PasswordTag.cleanTags();
          JOptionPane.showMessageDialog(this, deletedSuccessfully, informationCaption, JOptionPane.INFORMATION_MESSAGE);
          newPasswordEntry();
        } else {
          JOptionPane.showMessageDialog(this, errorOccured, errorCaption, JOptionPane.ERROR_MESSAGE);
        }
      } else {
        JOptionPane.showMessageDialog(this, errorOccured, errorCaption, JOptionPane.ERROR_MESSAGE);
      }
    }
  }

  private void newPasswordEntry() {
    passwordEntry = null;

    txtTitle.setText("");
    txtDescription.setText("");
    txtUsername.setText("");
    txtPassword.setText("");
    txtConfirmation.setText("");
    txtURL.setText("http://");
    txtTags.setText("");
    lblPassword.setText("");
    lblConfirmation.setText("");

    lblStatus.setText(newPasswordCaption);
    lblStatus.setForeground(StatusNewColor);

    btnDelete.setEnabled(false);
    txtTitle.requestFocus();
    initializePasswordValIcons();//have a tick in both fields.
    hideStars();
  }
  /*
   * initializes the icons for each passwords fields
   */

  private void initializePasswordValIcons() {

    this.confValLabel.setIcon(null);
  }

  private void about() {
    if (aboutDialog == null) {
      aboutDialog = new AboutDialog(this, true);
    }
    Utils.setCenterOfParent(this, aboutDialog);
    aboutDialog.setVisible(true);
  }

  private void importFromXML() {
    final JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileFilter(new XMLFileFilter());
    int answer = fileChooser.showOpenDialog(this);

    if (answer == JFileChooser.APPROVE_OPTION) {
      File file = fileChooser.getSelectedFile();

      if (file.isDirectory()) {
        JOptionPane.showMessageDialog(this, selectAFileNot, errorCaption, JOptionPane.ERROR_MESSAGE);
        return;
      } else if (!Utils.getFileExtension(file).equals("xml")) {
        JOptionPane.showMessageDialog(this, invalidFileExtension, errorCaption, JOptionPane.ERROR_MESSAGE);
        return;
      }

      try {
        String key = null;
        JTextField txtKey = new JTextField();
        txtKey.addAncestorListener(new RequestFocusListener());
        int answerKey = JOptionPane.showOptionDialog(this, new Object[]{pleaseEnterTheKey, txtKey}, decryptionKey, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{okCaption, cancelCaption}, okCaption);
        if (answerKey == JOptionPane.OK_OPTION && txtKey.getText() != null) {
          key = txtKey.getText();
        }

        if (key != null) {
          //boolean encryptAllFields = JOptionPane.showConfirmDialog(this, areAllFieldsEncrypted, security, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION;
          int answer1 = JOptionPane.showOptionDialog(this, areAllFieldsEncrypted, security, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[]{yesCaption, noCaption}, yesCaption);
          boolean encryptAllFields = answer1 == JOptionPane.YES_OPTION;

          byte[] byteKey = key.getBytes("UTF8");
          if (byteKey.length == 16) {
            ImportDialog importDialog = new ImportDialog(this, true, file, key, encryptAllFields);
            importDialog.setVisible(true);
          } else {
            JOptionPane.showMessageDialog(this, invalidDecryptionKey, errorCaption, JOptionPane.ERROR_MESSAGE);
          }
        }
      } catch (UnsupportedEncodingException ex) {
        JOptionPane.showMessageDialog(this, invalidDecryptionKey, errorCaption, JOptionPane.ERROR_MESSAGE);
        Logger.log(ex.getMessage());
      }
    }
  }

  private void exportFromXML() {
    final JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileFilter(new XMLFileFilter());
    int answer = fileChooser.showSaveDialog(this);

    if (answer == JFileChooser.APPROVE_OPTION) {
      File file = fileChooser.getSelectedFile();
      if (file.getName().indexOf(".") < 0) {
        file = new File(file.getAbsolutePath() + ".xml");
      }

      int overwrite = JOptionPane.YES_OPTION;
      if (file.exists()) {
        overwrite = JOptionPane.showConfirmDialog(this, "Overwrite the existing file?", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
      }
      if (file.isDirectory()) {
        JOptionPane.showMessageDialog(this, "Select a file, not a directory!", "Error", JOptionPane.ERROR_MESSAGE);
        return;
      } else if (!Utils.getFileExtension(file).equals("xml")) {
        JOptionPane.showMessageDialog(this, "Invalid file extension!", "Error", JOptionPane.ERROR_MESSAGE);
        return;
      }
      if (overwrite == JOptionPane.YES_OPTION) {
        try {
          String key = JOptionPane.showInputDialog(this, "Please enter a 16-letter English word as encryption key:\n(You can enter a 8-letter internationl word instead)", "Encryption Key", JOptionPane.INFORMATION_MESSAGE);
          if (key != null) {
            byte[] byteKey = key.getBytes("UTF8");
            if (byteKey.length == 16) {
              boolean encryptAllFields = JOptionPane.showConfirmDialog(this, "Encrypt all fields?", "Security", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION;
              ExportDialog exportDialog = new ExportDialog(this, true, file, key, encryptAllFields);
              exportDialog.setVisible(true);
            } else {
              JOptionPane.showMessageDialog(this, "Invalid Encryption Key!", "Error", JOptionPane.ERROR_MESSAGE);
            }
          }
        } catch (UnsupportedEncodingException ex) {
          JOptionPane.showMessageDialog(this, "Invalid Encryption Key!", "Error", JOptionPane.ERROR_MESSAGE);
          Logger.log(ex.getMessage());
        }
      }
    }
  }

  private void showBaloon(JComponent component, String message, Color backgroundColor, Color borderColor, int timeout) {
    BalloonTipStyle balloonTipLook = new RoundedBalloonStyle(10, 10, backgroundColor, borderColor);
    BalloonTip balloonTip = null;
    if (timeout > 0) {
      balloonTip = new BalloonTip(component, message, balloonTipLook, Orientation.RIGHT_ABOVE, AttachLocation.ALIGNED, 10, 10, false);
      TimingUtils.showTimedBalloon(balloonTip, timeout);
    } else {
      balloonTip = new BalloonTip(component, message, balloonTipLook, Orientation.RIGHT_ABOVE, AttachLocation.ALIGNED, 10, 10, true);
    }
    balloonTip.setVisible(true);
  }

  private void showStars(String password) {
    PasswordAnalyser passwordAnalyser = new PasswordAnalyser(password);
    int strength = passwordAnalyser.getPoints();

    String iconName = "";

    if (strength < 2) {
      iconName = "1stars.png";
    } else if (strength < 4) {
      iconName = "2stars.png";
    } else if (strength < 6) {
      iconName = "3stars.png";
    } else if (strength < 7) {
      iconName = "4stars.png";
    } else if (strength < 9) {
      iconName = "5stars.png";
    } else if (strength >= 9) {
      iconName = "6stars.png";
    }

    URL url = ResourceLoader.class.getResource(iconName);
    lblStrength.setIcon(new ImageIcon(url));
  }

  private void hideStars() {
    URL url = ResourceLoader.class.getResource("0stars.png");
    lblStrength.setIcon(new ImageIcon(url));
  }

  private void lockTimerActionPerformed() {
    Domain domain = Domain.getInstance();
    if (domain.minutesOfLastDBConnection() >= 5) {
      if (!this.locked) {
        lock();
      }
    }
  }

  private void lock() {
    this.locked = true;
    pnlMain.setVisible(false);
  }

  private void unlock() {
    LoginDialog loginDialog = new LoginDialog(this, true, true);
    loginDialog.setVisible(true);
    if (loginDialog.getLoginResult() == LoginDialog.LOGIN_CANCELED) {
      Logger.log("Unlock cenceled.");
      loginDialog.dispose();
      loginDialog = null;
      System.exit(0);
    } else {
      this.locked = false;
      Logger.log("Successfull unlock.");
      loginDialog.dispose();
      loginDialog = null;
      pnlMain.setVisible(true);
    }
  }

  private void checkForNewerVersion() throws ParserConfigurationException, SAXException, IOException {
    VersionChecker versionChecker = new VersionChecker(this);
    Thread thread = new Thread(versionChecker);
    thread.start();
  }

  private void showBrows() {
    BrowseDialog browsDialog = new BrowseDialog(this, true);
    browsDialog.setVisible(true);
    browsDialog.dispose();
  }

  private void authenticate() {
    Domain domain = Domain.getInstance();
    String currentPassword = domain.getSetting("password", null);
    if (currentPassword != null && currentPassword.length() > 0) {
      LoginDialog loginDialog = new LoginDialog(this, true, true);
      loginDialog.setVisible(true);
      if (loginDialog.getLoginResult() == LoginDialog.LOGIN_CANCELED) {
        Logger.log("Login cenceled.");
        loginDialog.dispose();
        loginDialog = null;
        System.exit(0);
      } else {
        Logger.log("Successfull login.");
        loginDialog.dispose();
        loginDialog = null;
        if (timerToolbarDecoration != null) {
          timerToolbarDecoration.start();
        }
      }
    }
    pnlMain.setVisible(true);
  }

  //<editor-fold defaultstate="collapsed" desc="GETTERS & SETTERS">
  public PasswordEntry getPasswordEntry() {
    return passwordEntry;
  }

  public void setPasswordEntry(PasswordEntry passwordEntry) {
    this.passwordEntry = passwordEntry;
  }
  //</editor-fold>

  //<editor-fold defaultstate="collapsed" desc="Methods of Implamentating Interfaces">
  @Override
  public void lostOwnership(Clipboard clipboard, Transferable contents) {
    throw new UnsupportedOperationException("Not supported yet.");
  }
  //</editor-fold>

  /*
   * public static void main(String[] args) throws FileNotFoundException,
   * IOException { Properties properties = new Properties();
   * properties.setProperty("systemLookAndFeel", "true");
   *
   * File file = new File("settings.properties"); FileOutputStream
   * fileOutputStream = new FileOutputStream(file);
   * properties.store(fileOutputStream, "http://mypasswords7.sf.net"); }
   *
   */
  private void btnPasswordGeneratorActionPerform(ActionEvent evt) {
    if (passwordGeneratorDialog == null) {
      passwordGeneratorDialog = new PasswordGeneratorDialog(this, false);
    }
    Utils.setCenterOfParent(this, passwordGeneratorDialog);
    passwordGeneratorDialog.setVisible(true);
  }

  private void txtTitleKeyPress(KeyEvent evt) {
    if (txtTitle.getText().length() == 1) {//(txtTitle.getText().length() <= 1 && txtTitle.getText().length() > 0) {
      if (showTitleBaloon) {
        showBaloon(txtTitle, "<html>Use <b>CTRL + SPACE</b> for auto-completion.<br />(Saved passwords)</html>", new Color(240, 240, 240, 250), new Color(200, 200, 200, 255), 5000);
        showTitleBaloon = false;
      } else {
        showBaloon(txtTitle, "<html>Use <b>CTRL + SPACE</b> for auto-completion.<br />(Saved passwords)</html>", new Color(240, 240, 240, 250), new Color(200, 200, 200, 255), 2000);
      }
    } else {
      Domain domain = Domain.getInstance();
      int key = evt.getKeyCode();
      int mod = evt.getModifiersEx();
      if (key == 32 && mod == 128) {  // CTRL + SPACE
        suggestPasswordEntry();
        showTitleBaloon = false;
        domain.setSetting("show_title_baloon", "false", null);
      }
      if (key == 10) {
        txtTitle.setSelectionStart(txtTitle.getText().length());
        txtTitle.setSelectionEnd(txtTitle.getText().length());
      }
    }
  }

  private void txtTagsKeyPress(KeyEvent evt) {
    int key = evt.getKeyCode();
    if (key == 44) { // CAMA      
      txtTags.setSelectionStart(txtTags.getText().length());
      txtTags.setSelectionEnd(txtTags.getText().length());
    }
  }

  private void txtTagsKeyRelease(KeyEvent evt) {
    int key = evt.getKeyCode();

    if (key >= 33 && key <= 40) { // ARROW KEYS      
      return;
    } else if (key == 8) {      // BACKSPACE
      return;
    } else if (key == 32) {     // SPACE       
      return;
    } else if (key == 10) { // ENTER      
      txtTags.setSelectionStart(txtTags.getText().length());
      txtTags.setSelectionEnd(txtTags.getText().length());
    }

    String lastTag = "";
    StringTokenizer tokenTags = new StringTokenizer(txtTags.getText(), ",");
    while (tokenTags.hasMoreTokens()) {
      lastTag = tokenTags.nextToken().trim();
    }

    if (lastTag.length() > 1) {
      String candidTag = searchInTags(lastTag);
      if (candidTag.length() > 0) {
        String restOfCandidTag = Utils.getRestOfStrings(lastTag, candidTag);
        txtTags.setText(txtTags.getText() + restOfCandidTag);
        txtTags.setSelectionStart(txtTags.getText().lastIndexOf(restOfCandidTag));
        txtTags.setSelectionEnd(txtTags.getText().length());
      }
    }
  }

  private void checkLanguages() throws LanguageException {
    availableLanguages = LanguageManager.getAvailableLanguages();

    if (availableLanguages.length > 0) {
      cmbLanguages = new JComboBox();
      cmbLanguages.setBackground(tlbMain.getBackground());
      cmbLanguages.addItem("EN");
      for (int i = 0; i < availableLanguages.length; i++) {
        String language = availableLanguages[i];
        language = language.substring(0, language.indexOf(".")).toUpperCase();
        cmbLanguages.addItem(language);
      }
    }

    if (cmbLanguages != null) {
      cmbLanguages.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
          selectedLanguage = (String) cmbLanguages.getSelectedItem();
          changeLanguage();
        }
      });
      tlbMain.add(cmbLanguages);
      timerToolbarDecoration = new Timer(10, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
          //System.out.println("timer");
          Point cmbLanguagesPosition = cmbLanguages.getLocation();
          Dimension toolbarSize = tlbMain.getSize();
          Point btnAboutPosition = btnAbout.getLocation();
          Dimension btnAboutSize = btnAbout.getSize();
          int speceWidth = toolbarSize.width - (btnAboutSize.width + btnAboutPosition.x + Math.min(50, cmbLanguagesPosition.x));
          Dimension pnlSpaceSize = new Dimension(speceWidth - 5, 0);
          JPanel pnlSpace = new JPanel();
          pnlSpace.setPreferredSize(pnlSpaceSize);
          pnlSpace.setBackground(tlbMain.getBackground());
          tlbMain.remove(cmbLanguages);
          tlbMain.add(pnlSpace);
          //pnlSpace.setVisible(false);
          tlbMain.add(cmbLanguages);
          cmbLanguages.setVisible(false);
          cmbLanguages.setVisible(true);
          timerToolbarDecoration.stop();
        }
      });
    }
  }

  private void changeLanguage() {
    if (englishLanguage == null) {
      englishLanguage = new Properties();
      englishLanguage.setProperty("direction", "ltr");
      englishLanguage.setProperty("NewPassword", newPasswordCaption);
      englishLanguage.setProperty("UpdatePassword", updatePasswordCaption);
      englishLanguage.setProperty("Title", "Title");
      englishLanguage.setProperty("Description", "Description");
      englishLanguage.setProperty("Username", "Username");
      englishLanguage.setProperty("Password", "Password");
      englishLanguage.setProperty("Confirmation", "Confirmation");
      englishLanguage.setProperty("Strength", "Strength");
      englishLanguage.setProperty("URL", "URL");
      englishLanguage.setProperty("Tags", "Tags");
      englishLanguage.setProperty("Save", "Save");
      englishLanguage.setProperty("New", "New");
      englishLanguage.setProperty("ShowPassword", "Show Password");
      englishLanguage.setProperty("DeletePassword", "Delete Password");
      englishLanguage.setProperty("Search", "Search");
      englishLanguage.setProperty("Browse", "Browse");
      englishLanguage.setProperty("ImportFromXMLFile", "Import from XML file");
      englishLanguage.setProperty("ExportToXMLFile", "Export to XML file");
      englishLanguage.setProperty("ChangePassword", "Change Password");
      englishLanguage.setProperty("PasswordGenerator", "Password Generator");
      englishLanguage.setProperty("Encryptor", "Encryptor");
      englishLanguage.setProperty("AboutMyPasswords", "About MyPasswords");
      englishLanguage.setProperty("Search", "Search");
      englishLanguage.setProperty("Tag", "Tag");
      englishLanguage.setProperty("Count", "Count");
      englishLanguage.setProperty("Error", errorCaption);
      englishLanguage.setProperty("Information", informationCaption);
      englishLanguage.setProperty("Delete", deleteCaption);
      englishLanguage.setProperty("InvalidDecryptionKey", invalidDecryptionKey);
      englishLanguage.setProperty("AreAllEncrypted", areAllFieldsEncrypted);
      englishLanguage.setProperty("PleaseEnterTheKeyWhichYouHaveEncryptedTheFileWith", pleaseEnterTheKey);
      englishLanguage.setProperty("PasswordDeletedSuccessfully", deletedSuccessfully);
      englishLanguage.setProperty("ErrorOccured", errorOccured);
      englishLanguage.setProperty("DoYouWantToDeleteThePassword", doYouWantToDelete);
      englishLanguage.setProperty("PasswordSaved", passwordSaved);
      englishLanguage.setProperty("Warning", warningCaption);
      englishLanguage.setProperty("YouMustChooseATitle", youMustChooseATitle);
      englishLanguage.setProperty("SelectAFileNot", selectAFileNot);
      englishLanguage.setProperty("InvalidFileExtension", invalidFileExtension);
      englishLanguage.setProperty("DecryptionKey", decryptionKey);
      englishLanguage.setProperty("Security", security);
      englishLanguage.setProperty("Yes", yesCaption);
      englishLanguage.setProperty("No", noCaption);
      englishLanguage.setProperty("Cancel", cancelCaption);
      englishLanguage.setProperty("OK", okCaption);
      englishLanguage.setProperty("ConfirmDoesNotMatch", confirmDoesNotMatch);

    }
    if (selectedLanguage.equalsIgnoreCase("en")) {
      currentLanguage = englishLanguage;
    } else {
      String languageName = selectedLanguage.toLowerCase() + ".lang";
      try {
        Properties language = LanguageManager.getLanguage(languageName);
        if (language != null) {
          currentLanguage = language;
        }
      } catch (IOException ex) {
        JOptionPane.showMessageDialog(this, "Loading language file '" + languageName + "' failed!", "Error", JOptionPane.WARNING_MESSAGE);
      }
    }
    String direction = currentLanguage.getProperty("direction");
    if (direction != null) {
      setDirection(direction);
    }

    newPasswordCaption = currentLanguage.getProperty("NewPassword");
    updatePasswordCaption = currentLanguage.getProperty("UpdatePassword");

    lblTitle.setText(currentLanguage.getProperty("Title") + ":");
    lblDescription.setText(currentLanguage.getProperty("Description") + ":");
    lblUsername.setText(currentLanguage.getProperty("Username") + ":");
    lblPassword2.setText(currentLanguage.getProperty("Password") + ":");
    lblConfirmation2.setText(currentLanguage.getProperty("Confirmation") + ":");
    lblStrength2.setText(currentLanguage.getProperty("Strength") + ":");
    lblURL.setText(currentLanguage.getProperty("URL") + ":");
    lblTags.setText(currentLanguage.getProperty("Tags") + ":");
    btnSave.setText(currentLanguage.getProperty("Save"));
    btnNew.setText(currentLanguage.getProperty("New"));
    btnShowPassword.setToolTipText(currentLanguage.getProperty("ShowPassword"));
    btnDelete.setToolTipText(currentLanguage.getProperty("DeletePassword"));
    btnSearch.setToolTipText(currentLanguage.getProperty("Search"));
    btnBrows.setToolTipText(currentLanguage.getProperty("Browse"));
    btnImport.setToolTipText(currentLanguage.getProperty("ImportFromXMLFile"));
    btnExport.setToolTipText(currentLanguage.getProperty("ExportToXMLFile"));
    btnChangePassword.setToolTipText(currentLanguage.getProperty("ChangePassword"));
    btnPasswordGenerator.setToolTipText(currentLanguage.getProperty("PasswordGenerator"));
    btnEncryptor.setToolTipText(currentLanguage.getProperty("Encryptor"));
    btnAbout.setToolTipText(currentLanguage.getProperty("AboutMyPasswords"));
    errorCaption = currentLanguage.getProperty("Error");
    informationCaption = currentLanguage.getProperty("Information");
    deleteCaption = currentLanguage.getProperty("Delete");
    invalidDecryptionKey = currentLanguage.getProperty("InvalidDecryptionKey");
    areAllFieldsEncrypted = currentLanguage.getProperty("AreAllEncrypted");
    pleaseEnterTheKey = currentLanguage.getProperty("PleaseEnterTheKeyWhichYouHaveEncryptedTheFileWith");
    deletedSuccessfully = currentLanguage.getProperty("PasswordDeletedSuccessfully");
    errorOccured = currentLanguage.getProperty("ErrorOccured");
    doYouWantToDelete = ("<html>" + currentLanguage.getProperty("DoYouWantToDeleteThePassword") + "</html>").replace("[password name]", "<b>%s</b>");
    passwordSaved = currentLanguage.getProperty("PasswordSaved");
    warningCaption = currentLanguage.getProperty("Warning");
    youMustChooseATitle = currentLanguage.getProperty("YouMustChooseATitle");
    selectAFileNot = currentLanguage.getProperty("SelectAFileNot");
    invalidFileExtension = currentLanguage.getProperty("InvalidFileExtension");
    decryptionKey = currentLanguage.getProperty("DecryptionKey");
    security = currentLanguage.getProperty("Security");
    noCaption = currentLanguage.getProperty("No");
    yesCaption = currentLanguage.getProperty("Yes");
    confirmDoesNotMatch = currentLanguage.getProperty("ConfirmDoesNotMatch");
    okCaption = currentLanguage.getProperty("OK");
    cancelCaption = currentLanguage.getProperty("Cancel");


    setStatusLabel();
    refresh();
  }

  private void setDirection(String direction) {
    if (direction.equals("rtl")) {
      setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
      pnlMain.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
      tlbMain.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
      cmbLanguages.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

      for (int i = 0; i < pnlMain.getComponents().length; i++) {
        Component component = pnlMain.getComponents()[i];
        component.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
      }
    } else if (direction.equals("ltr")) {
      setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
      pnlMain.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
      tlbMain.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
      cmbLanguages.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);

      for (int i = 0; i < pnlMain.getComponents().length; i++) {
        Component component = pnlMain.getComponents()[i];
        component.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
      }
    }
  }

  private void refresh() {
    pnlMain.setVisible(false);
    pnlMain.setVisible(true);

    tlbMain.setVisible(false);
    tlbMain.setVisible(true);
  }

  private void setStatusLabel() {
    if (lblStatus.getForeground().equals(StatusNewColor)) {
      lblStatus.setText(newPasswordCaption);
    } else if (lblStatus.getForeground().equals(StatusUpdateColor)) {
      lblStatus.setText(updatePasswordCaption);
    }
  }

  public Properties getCurrentLanguage() {
    return currentLanguage;
  }

  private void showEncryptor() {
    EncryptionDialog encryptionDialog = new EncryptionDialog(this, false);
    encryptionDialog.setVisible(true);
  }

  private void btnSettingsActionPerform(ActionEvent evt) {
    SettingsDialog settingsDialog = new SettingsDialog(this, false);
    settingsDialog.setVisible(true);
  }

  private void askForDonation() {
    Domain domain = Domain.getInstance();
    String donation = domain.getSetting("donation", null);
    if (donation == null) {
      String message = "<html>Thanks for using MyPasswords<br/><b>Do you want to donate to MyPasswords project?</b></html>";
      int answer = JOptionPane.showConfirmDialog(this, message, "Donation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
      if (answer == JOptionPane.YES_OPTION) {
        Utils.openURL("http://www.mypasswords7.com/donate");
      }
      domain.setSetting("donation", "1", null);
    }
  }

  private void displaySurvey() {
    if (!surveyDisplayed) {
      Calendar calendar = new GregorianCalendar();
      int day = calendar.get(Calendar.DAY_OF_WEEK);
      if (day == 7 || day == 1) {
        int minute = calendar.get(Calendar.MINUTE);
        int remainder = minute % 5;
        if (remainder == 0) {
          String message = "<html>Thanks for using MyPasswords<br/><b>Do you want to participate in our survey?</b></html>";
          int answer = JOptionPane.showConfirmDialog(this, message, "Survey", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
          if (answer == JOptionPane.YES_OPTION) {
            Utils.openURL("http://www.mypasswords7.com/survey");
          }
        }
      }
      surveyDisplayed = true;
    }
  }
}
